{
 "cells": [
  {
   "cell_type": "code",
   "id": "initial_id",
   "metadata": {
    "collapsed": true,
    "ExecuteTime": {
     "end_time": "2025-10-10T11:07:07.557644Z",
     "start_time": "2025-10-10T11:07:07.553536Z"
    }
   },
   "source": [
    "import os\n",
    "\n",
    "from dotenv import load_dotenv\n",
    "from langchain_core.messages import ToolMessage\n",
    "import json\n",
    "\n",
    "load_dotenv()\n",
    "\n",
    "kimi_model = os.getenv('KIMI_MODEL')"
   ],
   "outputs": [],
   "execution_count": 14
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-10-10T10:50:18.599951Z",
     "start_time": "2025-10-10T10:50:18.597088Z"
    }
   },
   "cell_type": "code",
   "source": [
    "from langchain_openai import ChatOpenAI\n",
    "from langgraph.graph import add_messages, StateGraph, START, END\n",
    "from typing_extensions import TypedDict, Annotated"
   ],
   "id": "57da3d4e760654af",
   "outputs": [],
   "execution_count": 12
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-10-10T10:49:38.550333Z",
     "start_time": "2025-10-10T10:49:28.474262Z"
    }
   },
   "cell_type": "code",
   "source": [
    "from langchain_tavily import TavilySearch\n",
    "\n",
    "tool = TavilySearch(max_results=3)\n",
    "tools = [tool]\n",
    "\n",
    "tool.invoke(\"在langgraph中，node是什么？\")"
   ],
   "id": "e8ac65c0a42cb7da",
   "outputs": [
    {
     "data": {
      "text/plain": [
       "{'query': '在langgraph中，node是什么？',\n",
       " 'follow_up_questions': None,\n",
       " 'answer': None,\n",
       " 'images': [],\n",
       " 'results': [{'url': 'https://zhuanlan.zhihu.com/p/1957429249926477413',\n",
       "   'title': 'LangGraph 详解系列1.1: 最简图案例（State/Edge/Node） - 知乎专栏',\n",
       "   'content': 'LangGraph 是一个用于构建有状态的多步骤应用的框架。它将应用程序建模为一个图（Graph），其中：. 节点（Node）：执行具体操作的函数; 边（',\n",
       "   'score': 0.8742601,\n",
       "   'raw_content': None},\n",
       "  {'url': 'https://blog.csdn.net/iCloudEnd/article/details/140789949',\n",
       "   'title': 'LangGraph 初学者指南：了解状态、节点和边原创 - CSDN博客',\n",
       "   'content': '* 博客 * 下载 * 学习 * 社区 * GitCode * InsCodeAI * 会议 AI 搜索 # LangGraph 初学者指南：了解状态、节点和边 知识大胖 于\\xa02024-07-30 10:18:39\\xa0发布 阅读量421 收藏 CC 4.0 BY-SA版权 分类专栏： NVIDIA GPU和大语言模型开发教程 文章标签： langgraph llm 版权声明：本文为博主原创文章，遵循 CC 4.0 BY-SA 版权协议，转载请附上原文出处链接和本声明。 本文链接： NVIDIA GPU和大语言模型开发教程 专栏收录该内容 1648 篇文章 ¥89.90 ¥99.00 订阅专栏 ## 简介 在本文中，我们将讨论 LangGraph 的基础知识。主要关注 LangGraph 的各个组件：State、Node 和 Edges，以及如何从这些组件构建完整的图。一旦我们理解了这些组件，我们将能够构建相对复杂的基于 LangGraph 的代理。 ## 首先，让我们了解各种组件，然后使用它们构建完整的图形。 节点：节点是图的基本构建块。每个节点代表处理当前状态的特定函数或操作。节点可以执行计算、修改状态或根据收到的输入生成输出。它们通常被定义为Python 函数或类，以当前状态作为输入并返回更新后的状态。 边：边定义节点之间的连接，确定图中的执行流程。它们指定一个节点的输出如何作为输入传递到另一个节点。边可以是正常的（直接将一个节点连接到另一个节点）或条件性的（根据某些标准路由到不同的节点）。它们在控制操作顺序以及图中节点如何相互交互方面起着至关重要的作用。 状态：在 LangGraph 中，状态是一种共享数据结构，可捕获应用程序的当前快照。它可以是任何 Python 类型，但通常是 TypedDict 或 Pydantic BaseModel。状态在 LangGraph 的功能中起着至关重要的作用，它使节点能够 SwiftUI开发大全 微信名片 了解本专栏 订阅专栏 解锁全文 确定要放弃本次机会？ 福利倒计时 立减 ¥ 普通VIP年卡可用 立即使用 知识大胖 关注 关注 点赞 * 踩 收藏 觉得还不错? 一键收藏 评论 * 分享 复制链接 分享到 QQ 分享到新浪微博 扫一扫 * 打赏 打赏 订阅专栏 知识大胖 你的鼓励将是我创作的最大动力 ¥1 ¥2 ¥4 ¥6 ¥10 ¥20 微信扫码添加好友或搜索 ID 复制微信 ID',\n",
       "   'score': 0.86331123,\n",
       "   'raw_content': None},\n",
       "  {'url': 'https://zhuanlan.zhihu.com/p/720864252',\n",
       "   'title': '初学LangGraph 之节点、边和状态 - 知乎专栏',\n",
       "   'content': '小结 本文介绍了LangGraph 的基本元素，节点（Nodes）、边（Edges）和状态（State），并展示了如何构建简单的图。 探讨了节点如何实现执行逻辑，边如何控制流程，以',\n",
       "   'score': 0.8232293,\n",
       "   'raw_content': None}],\n",
       " 'response_time': 0.72,\n",
       " 'request_id': '2d422ebe-0f21-422a-a86f-302d1c53cfb4'}"
      ]
     },
     "execution_count": 10,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "execution_count": 10
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-10-10T10:52:52.476389Z",
     "start_time": "2025-10-10T10:52:52.464884Z"
    }
   },
   "cell_type": "code",
   "source": [
    "class State(TypedDict):\n",
    "    messages: Annotated[list, add_messages] # add Reduce\n",
    "\n",
    "graph_builder = StateGraph(State)\n",
    "\n",
    "llm_with_tool = ChatOpenAI(model=kimi_model).bind_tools(tools)\n",
    "\n",
    "def chatbot(state: State):\n",
    "    return {\n",
    "        \"messages\":[llm_with_tool.invoke(state[\"messages\"])],\n",
    "    }\n",
    "\n",
    "graph_builder.add_node(\"chatbot\", chatbot)"
   ],
   "id": "ecde5705974f2401",
   "outputs": [
    {
     "data": {
      "text/plain": [
       "<langgraph.graph.state.StateGraph at 0x18911565450>"
      ]
     },
     "execution_count": 13,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "execution_count": 13
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-10-10T11:18:06.582230Z",
     "start_time": "2025-10-10T11:18:06.576093Z"
    }
   },
   "cell_type": "code",
   "source": [
    "class BasicToolNode:\n",
    "    \"\"\"一个节点，用于执行上一个 AI 消息中请求的工具。\"\"\"\n",
    "\n",
    "    def __init__(self, tools: list):\n",
    "        self.tools_by_name = {tool.name: tool for tool in tools}\n",
    "\n",
    "    def __call__(self, inputs: dict):\n",
    "        if messages := inputs.get(\"messages\", []):\n",
    "            message = messages[-1]\n",
    "        else:\n",
    "            raise ValueError(\"No message found in input\")\n",
    "\n",
    "        outputs = []\n",
    "\n",
    "        # 遍历最后一条 AIMessage 中的所有工具调用请求。一个 AI 消息可能请求调用多个工具。\n",
    "        for tool_call in message.tool_calls:\n",
    "            tool_result = self.tools_by_name[tool_call[\"name\"]].invoke(tool_call[\"args\"])\n",
    "\n",
    "            outputs.append(\n",
    "                ToolMessage(\n",
    "                    content=json.dumps(tool_result),\n",
    "                    name=tool_call[\"name\"],\n",
    "                    tool_call_id=tool_call[\"id\"],\n",
    "                )\n",
    "            )\n",
    "        return {\"messages\": outputs}\n",
    "\n",
    "tool_node = BasicToolNode(tools=[tool])\n",
    "graph_builder.add_node(\"tools\", tool_node)"
   ],
   "id": "4e64ffe6b19e9b18",
   "outputs": [
    {
     "data": {
      "text/plain": [
       "<langgraph.graph.state.StateGraph at 0x18911565450>"
      ]
     },
     "execution_count": 15,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "execution_count": 15
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-10-10T11:34:05.715542Z",
     "start_time": "2025-10-10T11:34:05.711808Z"
    }
   },
   "cell_type": "code",
   "source": [
    "def route_tools(state: State):\n",
    "    \"\"\"\n",
    "    如果上一条消息包含工具调用，则使用 conditional_edge 路由到 ToolNode；\n",
    "    否则，路由到终点。\n",
    "    \"\"\"\n",
    "    if messages := state.get(\"messages\", []):\n",
    "        ai_message = messages[-1]\n",
    "    else:\n",
    "        raise ValueError(f\"No message found in input state: {state}\")\n",
    "\n",
    "    # 如果ai消息中包含工具调用属性，并且要调用的工具数量大于0，则去tools节点\n",
    "    if hasattr(ai_message, \"tool_calls\") and len(ai_message.tool_calls) > 0:\n",
    "        return \"tools\"\n",
    "\n",
    "    return END"
   ],
   "id": "23a1f07b9524528e",
   "outputs": [],
   "execution_count": 16
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-10-10T11:36:11.798789Z",
     "start_time": "2025-10-10T11:36:11.794159Z"
    }
   },
   "cell_type": "code",
   "source": [
    "graph_builder.add_conditional_edges(\n",
    "    \"chatbot\",\n",
    "    route_tools,\n",
    "    {\"tools\": \"tools\", END: END} #如果返回的是tools，则去tools节点\n",
    ")\n",
    "\n",
    "graph_builder.add_edge(\"tools\", \"chatbot\")\n",
    "graph_builder.add_edge(START, \"chatbot\")\n",
    "\n",
    "graph = graph_builder.compile()"
   ],
   "id": "90cdf2cfee14a9f1",
   "outputs": [],
   "execution_count": 17
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-10-10T12:03:10.211908Z",
     "start_time": "2025-10-10T12:02:39.020409Z"
    }
   },
   "cell_type": "code",
   "source": [
    "def stream_graph_updates(user_input: str):\n",
    "    init_state = {\n",
    "        \"messages\": [\n",
    "            {\n",
    "                \"role\": \"user\",\n",
    "                \"content\": user_input,\n",
    "            }\n",
    "        ],\n",
    "    }\n",
    "    for dic in graph.stream(init_state):\n",
    "        for msgs_dict in dic.values():\n",
    "            ai_message = msgs_dict[\"messages\"][-1]\n",
    "            print(\"----------\")\n",
    "            print(f\"Assistant: {ai_message.content}\")\n",
    "            print(\"----------\")\n",
    "\n",
    "while True:\n",
    "    try:\n",
    "        user_input = input(\"User: \")\n",
    "        if user_input.lower() in [\"quit\", \"exit\", \"q\"]:\n",
    "            print(\"Goodbye\")\n",
    "            break\n",
    "\n",
    "        print(\"User: \"+user_input)\n",
    "        stream_graph_updates(user_input)\n",
    "\n",
    "    except:\n",
    "        user_input = \"What do you know about LangGraph?\"\n",
    "        print(\"User: \" + user_input)\n",
    "        stream_graph_updates(user_input)\n",
    "        break"
   ],
   "id": "9827b6884be30514",
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "User: what do you know about LangGraph?\n",
      "----------\n",
      "Assistant: I'll search for current information about LangGraph to provide you with the most accurate and up-to-date details.\n",
      "----------\n",
      "----------\n",
      "Assistant: {\"query\": \"LangGraph\", \"follow_up_questions\": null, \"answer\": null, \"images\": [], \"results\": [{\"url\": \"https://www.analyticsvidhya.com/blog/2024/07/langgraph-revolutionizing-ai-agent/\", \"title\": \"What is LangGraph? - Analytics Vidhya\", \"content\": \"LangGraph is a library built on top of Langchain that is designed to facilitate the creation of cyclic graphs for large language model (LLM) \\u2013 based AI agents.\\n   It views agent Objective Points about LangGraph and workflows as cyclic graph topologies, allowing for more variable and nuanced agent behaviors than linear execution models. [...] To sum up, LangGraph is a major advancement in the development of AI agents. It enables developers to push the limits of what\\u2019s possible with AI agents by eliminating the shortcomings of earlier systems and offering a flexible, graph-based framework for agent construction and execution. LangGraph is positioned to influence the direction of artificial intelligence significantly in the future. [...] Frameworks such as LangGraph are becoming increasingly important as AI develops. LangGraph is making the next generation of AI applications possible by offering a versatile and strong framework for developing and overseeing AI agents.\", \"score\": 0.92652357, \"raw_content\": null}, {\"url\": \"https://docs.langchain.com/oss/python/langgraph/overview\", \"title\": \"LangGraph Overview - Docs by LangChain\", \"content\": \"Trusted by companies shaping the future of agents - including Klarna, Replit, Elastic, and more - LangGraph is a low-level orchestration framework for building, managing, and deploying long-running, stateful agents.LangGraph is very low-level, and focused entirely on agent orchestration. Before using LangGraph, it is recommended you familiarize yourself with some of the components used to build agents, starting with models and tools. We will commonly use LangChain components throughout the\", \"score\": 0.9263638, \"raw_content\": null}, {\"url\": \"https://www.datacamp.com/tutorial/langgraph-tutorial\", \"title\": \"LangGraph Tutorial: What Is LangGraph and How to Use It?\", \"content\": \"LangGraph is a library within the LangChain ecosystem designed to tackle these challenges head-on. LangGraph provides a framework for defining, coordinating, and executing multiple LLM agents (or chains) in a structured manner.\\n\\nIt simplifies the development process by enabling the creation of cyclical graphs, which are essential for developing agent runtimes. With LangGraph, we can easily build robust, scalable, and flexible multi-agent systems. [...] For applications requiring autonomous decision-making, LangGraph enables the creation of agents that can perform tasks independently based on user inputs and predefined logic.\\n\\nThese agents can execute complex workflows, interact with other systems, and adapt to new information dynamically. LangGraph's structured framework ensures that each agent operates efficiently and effectively, making it suitable for tasks like automated customer support, data processing, and system monitoring. [...] LangGraph ensures agents execute in the correct order and that necessary information is exchanged seamlessly. This coordination is vital for complex applications where multiple agents need to work together to achieve a common goal. By managing the flow of data and the sequence of operations, LangGraph allows developers to focus on the high-level logic of their applications rather than the intricacies of agent coordination.\\n\\nWhy LangGraph?\", \"score\": 0.92620385, \"raw_content\": null}], \"response_time\": 1.69, \"request_id\": \"d0ffe839-22e9-43f3-b004-62a3326e81d9\"}\n",
      "----------\n",
      "----------\n",
      "Assistant: Based on my search, here's what I know about LangGraph:\n",
      "\n",
      "## What is LangGraph?\n",
      "\n",
      "**LangGraph** is a library built on top of LangChain that facilitates the creation of cyclic graphs for large language model (LLM)-based AI agents. It's designed to address the limitations of linear execution models by enabling more complex, stateful agent behaviors.\n",
      "\n",
      "## Key Features and Capabilities:\n",
      "\n",
      "1. **Cyclic Graph Architecture**: Unlike traditional linear workflows, LangGraph views agent workflows as cyclic graph topologies, allowing for more variable and nuanced agent behaviors.\n",
      "\n",
      "2. **Low-level Orchestration Framework**: It's a low-level framework focused entirely on agent orchestration, trusted by major companies like Klarna, Replit, and Elastic.\n",
      "\n",
      "3. **Multi-Agent Systems**: LangGraph enables the creation of robust, scalable, and flexible multi-agent systems where multiple LLM agents can work together.\n",
      "\n",
      "4. **Stateful Operations**: It supports long-running, stateful agents that can maintain context and memory across interactions.\n",
      "\n",
      "## Main Use Cases:\n",
      "\n",
      "- **Autonomous Decision-Making**: Creating agents that can perform tasks independently based on user inputs and predefined logic\n",
      "- **Complex Workflows**: Building applications that require multiple steps and decision points\n",
      "- **Multi-Agent Coordination**: Managing systems where multiple agents need to work together to achieve common goals\n",
      "- **Automated Systems**: Applications like automated customer support, data processing, and system monitoring\n",
      "\n",
      "## Benefits:\n",
      "\n",
      "- **Flexibility**: More adaptable than linear execution models\n",
      "- **Scalability**: Can handle complex, multi-step processes\n",
      "- **Coordination**: Ensures agents execute in the correct order with proper information exchange\n",
      "- **Developer Focus**: Allows developers to focus on high-level logic rather than agent coordination intricacies\n",
      "\n",
      "LangGraph represents a significant advancement in AI agent development, providing a graph-based framework that overcomes the limitations of earlier linear systems and enables more sophisticated AI applications.\n",
      "----------\n",
      "Goodbye\n"
     ]
    }
   ],
   "execution_count": 25
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 2
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython2",
   "version": "2.7.6"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
